<?php

namespace App\Http\Controllers;

use App\Model\Account;
use App\Model\TradeLog;

class AssetController extends Controller
{
    /**
     * 币种资产明细
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function coin()
    {
        // 人民币帐户
        $rmbAccount = Account::select(['coin_id', 'available', 'disabled'])
            ->where('user_id', request()->user()->id)
            ->where('coin_id', 0)
            ->first();

        // 拥有币种资产明细
        $accounts = Account::with(['coin' => function ($query) {
            $query->select('id', 'name');
        }])->select(['coin_id', 'available', 'disabled'])
            ->where('user_id', request()->user()->id)
            ->where('coin_id', '!=', 0)
            ->get();

        return response()->json(compact('rmbAccount', 'accounts'));
    }

    /**
     * 总资产、净资产
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function asset()
    {
        // 人民币帐户
        $rmbAccount = Account::select(['coin_id', 'available', 'disabled'])
            ->where('user_id', request()->user()->id)
            ->where('coin_id', 0)
            ->first();

        // 净资产
        $netAsset = $rmbAccount->available + $rmbAccount->disabled;

        // 拥有币种资产明细
        $coins = Account::select(['coin_id', 'available', 'disabled'])
            ->where('user_id', request()->user()->id)
            ->where('coin_id','!=',0)
            ->get();

        // 总资产
        $sum = $rmbAccount->available + $rmbAccount->disabled;
        foreach ($coins as $coin) {
            $lastTrade = TradeLog::where('coin_id', $coin->coin_id)->orderBy('created_at', 'desc')->first();
            if ($lastTrade) {
                $sum += $lastTrade->price * ($coin->available + $coin->disabled);
            }
        }

        return response()->json(compact('sum', 'netAsset'));
    }
}